const axios                         = require('axios');
const utils                         = require('utility');
const {readFilePrms, writeFilePrms} = require('../utils/fsPrms');

const appId     = 'wx8bbcc4d675dd42dd';
const appSecret = '3025c1419f22e502ca451e066b467f20';

const tokenUrl = `https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=${appId}&secret=${appSecret}`;

const getAccessTokenPrms = function () {
    return readFilePrms('./wx/access_token.json').then(res => {
        let cachedAccessTokenObj = JSON.parse(res.data);

        if (new Date().getTime() - cachedAccessTokenObj.time > 7000000) {
            return axios.get(tokenUrl).then(res => {
                let tokenData = {
                    time: new Date().getTime(),
                    rst: res.data.access_token
                };
                console.log(res.data);
                writeFilePrms('./wx/access_token.json', JSON.stringify(tokenData))
                    .then(res => {
                        console.log('token写入完成');
                    }).catch(err => {
                    console.log(err);
                });
                return res.data.access_token
            }).catch(err => {
                console.log('获取access_token出错！！！')
            })
        } else {
            console.log('读取缓存token');
            return cachedAccessTokenObj.rst
        }
    });
};

const getTicketPrms = function () {
    return readFilePrms('./wx/ticket.json').then(res => {
        let cachedTicketObj = JSON.parse(res.data);

        if (new Date().getTime() - cachedTicketObj.time > 7000000) {
            return getAccessTokenPrms().then(token => {
                let ticketUrl = `https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=${token}&type=jsapi`;
                return axios.get(ticketUrl)
            }).then(res => {
                let ticketData = {
                    time: new Date().getTime(),
                    rst: res.data.ticket
                };
                console.log(res.data);
                writeFilePrms('./wx/ticket.json', JSON.stringify(ticketData))
                    .then(res => {
                        console.log('ticket写入完成');
                    }).catch(err => {
                    console.log(err);
                });
                return res.data.ticket
            }).catch(err => {
                console.log('获取ticket出错！！！')
            });

        } else {
            console.log('读取缓存ticket');
            return cachedTicketObj.rst
        }
    });
};

const signIt = function (params) {
    let string1 = [];
    const keys  = Object.keys(params).sort();

    for (let key of keys) {
        string1.push(`${key}=${params[key]}`);
    }

    console.log(string1)

    return utils.sha1(string1.join('&'))
};

const generateConfig = function () {
    return getTicketPrms().then(jsapi_ticket => {
        let timestamp = parseInt(new Date().getTime() / 1000) + '';
        let noncestr  = Math.random().toString(36).substr(2, 15);
        let url       = 'http://wechat.chebutou.com.cn/';

        let params = {
            url,
            timestamp,
            noncestr,
            jsapi_ticket,
        };

        let signature = signIt(params);

        return {
            timestamp,
            signature,
            noncestr
        }
    });
};

module.exports = generateConfig;
